var imgadmin=0;

/*图片*/
////////////////////////////////////////
var lanLogin = '请先登录！';
var lanpicPostSel = '请您选择要上传的图片';
var lanpicPostupload = '图片上传中...';
var lanpicPostUploadts1 = '您只能上传';
var lanpicPostUploadTypets = 'jpg/gif/jpeg';
var lanpicPostUploadType1 = '格式的图片，';
var lanpicPostUploadSize= '且大小不能超过';
var lanpicPostUploadSizeVal= '500K！';
var lanpicPostUploadSeleType= '请选择正择的附件类型!';
var lanpicPostUploadSeleSize= '附件不能大于指定大小!';
var lanpicPostUploadError= '上传失败.请稍后重试!';
//检测图片
function checkImg(){	
	var obj=document.getElementById("uploadfile1");//获取上传图片
 	var file = obj.value;
	var ext = file.substring(file.lastIndexOf(".") + 1, file.length).toLowerCase();
	if(ext==''){
		alert(lanpicPostSel);
		return false;
	}else if(ext=='jpg'||ext=='gif'||ext=='jpeg'){
		jQuery("#msg").html(lanpicPostupload);
		return true;
	}else{
		alert(lanpicPostUploadts1+lanpicPostUploadTypets+lanpicPostUploadType1+lanpicPostUploadSize+lanpicPostUploadSizeVal);
		return false;
	}
}




//前台剪切头
// path 
//
function  cropimgs(data,imagenums,webPath,ww,hh,folder){
//alert(data.h);
	$("#maximg").show();
	$("#minimg").show();
	var minz=minZoomvar(170,data.w);
 var cropzoom = $('#cropzoom_container').cropzoom({
			
           width:700,//最小宽度//容器的宽
            height:550,//最小高度//容器的高
            bgColor: '#ccc',//容器的背景色
			overlayColor:'#000',//拖动时覆盖层的背景色
            enableRotation:true,//是否启用旋转滑块
            enableZoom:true,//是否启用缩放滑块
            zoomSteps:1,//设置步骤缩放滑杆
            rotationSteps:5,//设置步骤旋转滑块
            selector:{        
              x:0,//x 轴的值
              y:0,//y 轴的值
              w:170,
              h:170,
			 // Centered:true,
              aspectRatio:false,//调整时是否保持纵横比
              centered:true,//选择框定位于容器的中心
              borderColor:'blue',//边框的颜色
              borderColorHover:'yellow',//选择区域拖动时的边框颜色
              bgInfoLayer: '#fff',//这将设置信息层，在出现选择背景色
              infoFontSize: 10,//这将设置信息层，在选择显示的字体大小
              infoFontColor: 'blue',//这将设置信息层，在出现选择字体颜色
              showPositionsOnDrag: true,//true,//启用或禁用x、y轴的信息
              showDimetionsOnDrag: false,//true 启用或禁用高 宽的信息
              //maxHeight: data.h,//最大选择的高度
              //maxWidth: data.w//最大选择的宽		
              maxHeight: 550,//最大选择的高度
              maxWidth: 700//最大选择的宽	
            },
            image:{
                source:data.src,//图片路径
                width:data.w,//原始图像的宽
                height:data.h,//原始图像的高
                minZoom:minz,//图像最低缩小百分比
                maxZoom:200,//图像最大放大百分比
                rotation:0//图像旋转度
            }
        });
        $('#crop').click(function(){
		$('#docrop').click();
          cropzoom.send(webPath+'/admin/image.php/folder='+folder,'POST',{type:''},function(rta){ 
				$("#images_"+imagenums).attr("src",webPath+'/images/'+ww+'/'+hh+'/'+rta);
				$("#uploadImagesAhref_"+imagenums).attr("href",webPath+'/'+rta);
				$("#image_"+imagenums).val(rta);
				$('#maximg').remove();
				addhtml();
				//alert(--imgadmin)
				 
				//alert('fdsaf')
            });			
        });
        $('#restore').click(function(){
            cropzoom.restore();
        });	
}

function init(){
	$(".ui_content_wrap",parent.document).css({'height':500,'width':520});
}
function  minZoomvar(selectorw,width){
		
		var minz=(parseInt(selectorw)/parseInt(width)).toFixed(5)*100;
		return minz;
}

function addhtml(){
	
	var dhtml='<span class="pspr" id="maximg" style=" display:none" ><form id="form1" runat="server"><div class="images"><div id="cropzoom_container" class="cropimgsrc_id"></div><div style="clear: both"></div></div><div class="buttons"><div id="crop" class="send_data" > Crop Image  </div><div id="restore" class="restore_data">Image reset</div<div style="clear: both"></div></div></form></span>';
	$("#addimgcorp").html(dhtml);
}
function showtitledoc(title,thist){
	var val=$.trim(thist.value);
	if(val==''){
		thist.value=title;
	}else{
		thist.value=val;
	}
}

function hidetitledoc(title,thist){
	//var val=$.trim(thist.value);
	thist.value='';	
	//titledoc	
}


/*
 var upc = new uploadImages();
//实例化的名称
upc.newName = 'upc';
//表单id
upc.formId = 'myform';
//网址
upc.webPath = '__URL__';
//文件域名称
upc.fileInputName = 'upf1';
//显示区id
upc.displayId='_images';
//裁切显示区id
upc.corpDisplayId= '_perview'; 
//是否允许上传多个图片
upc.ismore=true;
//上传目录
upc.uploadFolder = 'drama';
upc.imageTypes='logo,img,plane|{%=implode(',',$imgTypes)%}';
//初始化内容
upc.content = '{%=implode(',',$imgContent)%}';
//上传地址
upc.formAction ='__URL__/admin/image.php/upload/fileInputName=upf1';
//删除图片自定义函数
upc.deleteFunction = function(imgs){
	$.post('http://drama/admin/image.php/deleteImage',{img:imgs},function(data){
		if(data=='success'){
			deleteFuntionState = true;
		}
			
	});
}
//初始化HTML
upc.initHTML();
 */
var _webPath = '';
var _imageNum = 1;
var _formObject = null;
var _formEnctype = 'application/x-www-form-urlencoded';
var __formAction = '';
var _imgWidth = 0 ;
var _imgHeight = 0;
var _uploadImageFolder = '';
var deleteFuntionState = false;
var deleteFuntionState_TimeOut = null;
function uploadImages(){
	
	//当前第几个
	this.imageNum = 1;
	
	//图片总数
	this._imageCount = 1;
	
	this.ismore = true;
	//图片块显示宽高
	this.imgWidth =145;
	this.imgHeight = 105;
	this.uploadFolder = '';
	this.newName = 'ups';
	//初始内容
	this.content = '';
	
	this.displayId='_images';
	this.corpDisplayId= '_perview';
	//表单名称id
	this.formId = '';
	this.formObject = null;
	this.webPath = '';
	
	//文件上传组件的名称
	this.fileInputName = '';
	
	//备份的表单ACTION url
	this._formAction = '';
	
	//附加参数 ［图片类别］    logo,img|logo,img,img,img
	this.imageTypes ='';
	
	this.formAction = '';
	
    //删除 回调方法
	this.deleteFunction = '';
	//删除方法默认为自带的方法？
	this.deleteFunctionInit = true;
	
	//添加一个新的图片块
	this.addHTML = function(){
		var html = '<div id="uploadImagesBox_'+this._imageCount+'" style="width:'+this.imgWidth+'px;padding-bottom:3px;float:left;text-align:center;">';
		html+= '<a href="javascript:void(0)" style="float:left"id="uploadImagesAhref_'+this._imageCount+'" target="_blank"><img id="images_'+this._imageCount+'" src="'+this.webPath+'/images/'+this.imgWidth+'/'+this.imgHeight+'/pic.gif" style="border:1px solid #ccc" /></a>';
		html+= '<span style="float:left;width:100%;">';
		html+= '		<a href="javascript:void(0)"onclick="'+this.newName+'.deleteImage('+this._imageCount+')"style="color:#333;margin-right:5px">删除</a>|';
		html+= '		<a href="javascript:void(0)"style="color:#333;" onclick="'+this.newName+'.upload('+this._imageCount+')">上传</a>';
		html+= '</span>';
		html+= '<input  size="1" name="uploadImages[]" id="image_'+this._imageCount+'" value="" type="hidden" />';
		html+= '</div>'
		$("#uploadImagesBoxss").append(html);
		this.addImageTypes(this._imageCount);
		this._imageCount++;
	}
	
	//初始化HTML块
	this.initHTML = function(){
		if(this.uploadFolder==''){
			alert('上传目录不能为空！');
			return false;
		}
		_uploadImageFolder = this.uploadFolder;
		_webPath = this.webPath;
		_imgWidth = this.imgWidth;
		_imgHeight = this.imgHeight;
		var html = '<div style="float:left;padding:5px;" id="uploadImagesBoxs">';
			if(this.ismore){
				html+='<span><a href="javascript:'+this.newName+'.addHTML();">添加一张图片</a></span>';
			}
			html+='<div id="uploadImagesBoxss"></div></div>';
		$("#"+this.displayId).html(html);
		
		if(this.content == '')
			this.addHTML();
		else{
			this.initContent();
		}
		
		//切图部分HTML
		html='<div id="addimgcorp">';
		html+='<span class="pspr" id="maximg" style="display:none">';                               
		html+='<div class="images">';
		html+='<div id="cropzoom_container"></div>';
		html+='<div style="clear: both"></div>';
		html+='</div>';
		html+='<div class="buttons">';
		html+='<div  id="crop" class="send_data" >';
		html+='Crop Image';  
		html+='</div>';
		html+='<div id="restore" class="restore_data">';
		html+='Image reset</div>';
		html+='<div style="clear: both"></div>';
		html+='</div>';
		html+='</span>';
		html+='</div>';
		$("#"+this.corpDisplayId).append(html);
		
		
		
	}
	
	////////添加附加参数input////////
	this.addImageTypes = function(index){
	
		if(this.imageTypes=='') return;
		//如果有内容，则自动匹配对应的附加类型
		var y='',c='',e='';
		if(this.content!=''){
			var y = this.imageTypes.split('|');
			var c = y[0].split(',');
			var e = y[1].split(',');
		}
		else
			var c = this.imageTypes.split(',');
		
		var html = '<select name="uploadImageTypes[]">';
		
		for(var i =0; i<c.length; i++){
			if(e!=''){
				if(c[i]==e[index-1])
					html+='<option value="'+c[i]+'" selected="selected">'+c[i]+'</option>';
				else
					html+='<option value="'+c[i]+'">'+c[i]+'</option>';
			}else{
				html+='<option value="'+c[i].replace('|','')+'">'+c[i].replace('|','')+'</option>';
			}
			
		}
		html+='</select>';
		
		$("#uploadImagesBox_"+index+" span").append(html);
	}
	
	////////////初始化内容////////
	this.initContent = function (){
		var c = this.content.split(',');
		
		for(var i =0; i<c.length; i++){
			var j = this._imageCount;
			this.addHTML();
			$("#images_"+j).attr('src',this.webPath+'/images/145/105/'+c[i]);
			$("#image_"+j).val(c[i]);
			$("#uploadImagesAhref_"+j).attr('href',this.webPath+'/'+c[i]);
		}
	}
	
	
	
	///////////上传图片////////////
	this.upload = function(num){
		
		this.imageNum = num;
		_imageNum = num;
		
		this.formObject = $("#"+this.formId);
		_formObject = this.formObject;
		this._formAction = this.formObject.attr('action');
		__formAction = this._formAction;
		if(this.formObject.attr('id')==undefined){
			alert('表单id不存在:'+this.formId);
			return false;
		}
			
		
		if($("input[name='"+this.fileInputName+"']").val()==''){
			alert('请选择将要上传的图片！');
			return false;
		}
		//如果已存在图片
		if($("#image_"+num).val()!=''){
			this.deleteFunction($("#image_"+num).val());
		}

		$("#msg").html("send....");
		this.formObject.attr({'action':this.formAction,'enctype':'multipart/form-data'});
		var options = {
			dataType: 'json_encode',
			success:      this.doSuccess//成功时回调
		};
		this.formObject.ajaxSubmit(options);	
	}
	
	
	//上传成功后回调
	this.doSuccess = function(data){
		_formObject.attr({'action':__formAction,'enctype':_formEnctype});
		data = eval('('+data+')');
		cropimgs(data,_imageNum,_webPath,_imgWidth,_imgHeight,_uploadImageFolder);
		$("#msg").html("");
	}
	
	
	
	//删除BOX
	this.deleteImage = function(num){

		//是否已上传图片?
		if($("#image_"+num).val()!='' && confirm('确定需要删除已上传的图片？它将从服务器上删除！')===true){
			if(typeof(this.deleteFunction)=='function'){
				this.deleteFunction($("#image_"+num).val());
				/////////检查删除方法状态 成功时 删除图片box
				deleteFuntionState_TimeOut = setTimeout('deleteFuntionStateCheck('+num+')',1000);
			}else
				alert('deleteFunction not a function.');
			
		}else if($("#image_"+num).val()==''){
			$("#uploadImagesBox_"+num).remove();
		}
	}
	
	////////是否使用默认删除函数？
	if(this.deleteFunctionInit){
		this.deleteFunction = function(imgs){
			$.post('/admin/image.php/deleteImage',{img:imgs},function(data){
				if(data=='success'){
					deleteFuntionState = true;
				}
					
			});
		}
	}
	
}
/////////检查删除方法状态 成功时 删除图片box
deleteFuntionStateCheck = function(num){
	if(deleteFuntionState){
		$("#uploadImagesBox_"+num).remove();
		clearTimeout(deleteFuntionState_TimeOut);
	}else{
		deleteFuntionState_TimeOut = setTimeout('deleteFuntionStateCheck('+num+')',1000);
	}
		
}
